<?php
namespace app\admin\controller;

use app\admin\tool\Parser;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleCate as ArticleCateModel;
use think\Loader;
use think\Request;

class Article extends Base{

    public function index(){

        $model = ArticleModel::where([])->order('add_time desc')->paginate(10);

        $this->data['title'] = '文章列表';
        $this->data['parser'] = new Parser();
        $this->data['model'] = $model;
        $this->data['column'] = $this->column();

        return view("",$this->data);
    }


    public function add(Request $request){

        $this->data['title'] = '添加文章';
        //如果多了 就用modal的方式
        $cate = ArticleCateModel::all();
        $this->data['cate'] = $cate;

        return view('',$this->data);
    }

    public function edit(Request $request){

        $id = $request->param("id");
        $cate = ArticleCateModel::all();

        $this->data['title'] = '编辑文章';
        $this->data['model'] = ArticleModel::get($id);
        $this->data['cate'] = $cate;

        return view('',$this->data);
    }


    /**
     * @param Request $request
     */
    public function create(Request $request){

        $data = $request->post();

        $validate = Loader::validate('Article');
        if(!$validate->scene('base_add')->check($data)){
            $this->error($validate->getError());
        }

        $data['add_time'] = $data['update_time'] = time();
        $data['op_user']  = $this->admin->id;

        $model = new ArticleModel();
        $model->data($data);
        if($model->allowField(true)->save()){
            $this->success("新增成功");
        }

        $this->error("操作失败");
    }


    /**
     * 文章跟新 不需要跟新操作人 操作人就是作者
     * @param Request $request
     */
    public function update(Request $request){
        $data = $request->post();
        if(empty($data['id'])){
            $this->error("操作失败");
        }

        $validate = Loader::validate('Article');
        if(!$validate->scene('base_add')->check($data)){
            $this->error($validate->getError());
        }
        $data['update_time'] = time();

        $model = new ArticleModel();
        if($model ->allowField(true)-> save($data,['id'=>$data['id']])){
            $this->success("更新成功");
        }

        $this->error("操作失败");
    }


    protected function column(){
        return [
            'title'       =>['name'=>'标题','fun'=>'text','options'=>''],
            'cid'         =>['name'=>'分类','fun'=>'text','options'=>''],
            'desc'        =>['name'=>'描述','fun'=>'text','options'=>''],
            'seo_title'   =>['name'=>'SEO标题','fun'=>'text','options'=>''],
            'seo_desc'    =>['name'=>'seo描述','fun'=>'text','options'=>''],
            'seo_keywords'=>['name'=>'seo关键词','fun'=>'text','options'=>''],
            'cover'       =>['name'=>'封面图','fun'=>'text','options'=>''],
            'add_time'    =>['name'=>'添加时间','fun'=>'datetime','options'=>[]]
        ];
    }

}